<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button v-if="checkPermission('excel_import')" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-if="checkPermission('excel_export')" type="danger" size="small" @click="updatauser">excel导出</el-button>
          <el-button v-if="checkPermission('p-em-add')" type="primary" size="small" @click="Adduserclick">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="userList">
          <el-table-column label="序号" type="index" :index="indexList" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <img v-imgess="defaultImage" :src="row.staffPhoto||defaultImage" alt="" class="avatr">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="mployments" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ timeOfEntryess(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button v-if="checkPermission('p-em-look')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button v-if="checkPermission('assign-role')" type="text" size="small" @click="showcloselo(row.id)">分配角色</el-button>
              <el-button v-if="checkPermission('del_emp')" type="text" size="small" @click="delClick(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[5, 10, 20, 30]"
            layout="total,sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <EmploYs :show-dialog.sync="showloding" />
      <AssignRole :showcloselog.sync="showcloselog" :user-i-d-r="userIDR" />
    </div>
  </div>
</template>

<script>
import EmploYs from '@/views/employees/employt/index.vue'
import dayjs from 'dayjs'
import mployment from '@/constant/employees'
import { UserListAPI, delListAPI } from '@/api/empoly'
import AssignRole from '@/views/employees/employt/assign-role.vue'
export default {
  name: 'Dashboard',
  components: {
    EmploYs,
    AssignRole
  },
  data() {
    return {
      page: 1, // 当前页
      size: 10, // 每页数量
      userList: [],
      total: 0,
      userIDR: '',
      showloding: false,
      showcloselog: false,
      defaultImage: 'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401'
    }
  },
  created() {
    this.UserListAPI()
  },
  methods: {
    /**
     *
     */
    checkPermission(key) {
      return this.$store.getters.roles.points.includes(key)
    },
    /**
     * 获取员工列表
     */
    async UserListAPI() {
      const { data: res } = await UserListAPI({
        page: this.page,
        size: this.szie
      })
      // console.log(res)
      this.userList = res.rows// 赋值数据
      this.total = res.total// 赋值总条数
    },
    /**
     * 格式化聘用形式
     */
    mployments(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      const onj = mployment.hireType.find(item => item.id === cellValue)
      return onj ? onj.value : ''
    },
    /**
     * 每页总条数改变触发
     */
    handleSizeChange(val) {
      this.size = val
      this.page = 1
      this.UserListAPI()
    },
    /**
     * 当前页发生改变时触发
     */
    handleCurrentChange(val) {
      this.page = val
      this.UserListAPI()
    },
    /**
     * 处理分页序号
     */
    indexList(index) {
      // console.log(index)
      return (this.page - 1) * this.size + index + 1
    },
    /**
     * 修改时间格式
     */
    timeOfEntryess(value) {
      // console.log(value)
      return value ? dayjs(value).format('YYYY-MM-DD') : ''
    },
    /**
     * 删除员工
     */
    async delClick(id) {
      this.$confirm('确认删除此员工信息嘛', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        await delListAPI(id)
        if (this.userList.length === 1 && this.page > 1) {
          this.page--
        }
        this.UserListAPI()
        this.$message.success('删除成功')
      })
    },
    /**
     * 点击显示添加弹窗
     */
    Adduserclick() {
      this.showloding = true
    },
    /**
     * 点击导出表单
     */
    async  updatauser() {
      const { data: { rows }} = await UserListAPI({
        page: this.page,
        size: this.szie
      })
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const dataArr = this.formatJson(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表格的头部
          // 二维数组 [ [], [], [] ]
          data: dataArr,
          filename: '学生信息表', // 导出的excel文件名
          autoWidth: true, // 是否开启单元格宽度自适应
          bookType: 'xlsx' // 类型
        })
      })
    },
    // 将表头数据和数据进行对应
    formatJson(rows, headersArr, headersRelations) {
      // [
      //   [ 值1, 值2, 值3, ... ]
      // ]
      const resultsArr = rows.map(item => {
        const arr = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = this.timeOfEntryess(value)
          } if (englishKey === 'formOfEmployment') {
            const obj = mployment.hireType.find(obj => obj.id === +value)
            value = obj ? obj.value : '未知'
          }
          arr.push(value)
        })
        return arr
      })
      return resultsArr
    },
    /**
     * 点击显示分配角色弹层
     */
    async  showcloselo(id) {
      this.showcloselog = true
      this.userIDR = id
    }
  }
}
</script>

<style lang="scss" scoped>
    .avatr {
      width: 70px;
      height: 70px;
      border-radius: 50%;
  }
</style>
